#include "Optimizer.h"
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <functional>

// ==================== ConstantFoldingOptimizer 实现 ====================

bool ConstantFoldingOptimizer::isConstant(ASTNode* node) {
    if (!node) return false;

    if (node->type == "NumLiteral") {
        return true;
    }

    // 扩展支持的表达式类型
    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "RelExpr" || node->type == "LAndExpr" ||
        node->type == "LOrExpr" || node->type == "UnaryExpr") {
        return node->children.size() == 2 &&
               isConstant(node->children[0].get()) &&
               isConstant(node->children[1].get());
    }

    // 支持一元运算
    if (node->type == "UnaryExpr" && node->children.size() == 1) {
        return isConstant(node->children[0].get());
    }

    return false;
}

int ConstantFoldingOptimizer::evaluateConstant(ASTNode* node) {
    if (!node) return 0;

    if (node->type == "NumLiteral") {
        return std::stoi(node->value);
    }

    // 扩展支持的表达式类型和操作符
    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "RelExpr" || node->type == "LAndExpr" ||
        node->type == "LOrExpr") {

        if (node->children.size() != 2) return 0;

        int left = evaluateConstant(node->children[0].get());
        int right = evaluateConstant(node->children[1].get());

        // 算术运算
        if (node->value == "+") {
            return left + right;
        } else if (node->value == "-") {
            return left - right;
        } else if (node->value == "*") {
            return left * right;
        } else if (node->value == "/") {
            return right != 0 ? left / right : 0;
        } else if (node->value == "%") {
            return right != 0 ? left % right : 0;
        }
        // 比较运算
        else if (node->value == "==") {
            return left == right ? 1 : 0;
        } else if (node->value == "!=") {
            return left != right ? 1 : 0;
        } else if (node->value == "<") {
            return left < right ? 1 : 0;
        } else if (node->value == "<=") {
            return left <= right ? 1 : 0;
        } else if (node->value == ">") {
            return left > right ? 1 : 0;
        } else if (node->value == ">=") {
            return left >= right ? 1 : 0;
        }
        // 逻辑运算
        else if (node->value == "&&") {
            return (left != 0) && (right != 0) ? 1 : 0;
        } else if (node->value == "||") {
            return (left != 0) || (right != 0) ? 1 : 0;
        }
    }

    // 支持一元运算
    if (node->type == "UnaryExpr" && node->children.size() == 1) {
        int operand = evaluateConstant(node->children[0].get());

        if (node->value == "!") {
            return operand == 0 ? 1 : 0;
        } else if (node->value == "-") {
            return -operand;
        } else if (node->value == "+") {
            return operand;
        }
    }

    return 0;
}

bool ConstantFoldingOptimizer::applyAlgebraicOptimizations(ASTNode* node) {
    if (!node || node->children.size() != 2) return false;

    ASTNode* left = node->children[0].get();
    ASTNode* right = node->children[1].get();

    // 加法恒等式优化
    if (node->type == "AddExpr") {
        // x + 0 = x
        if (right->type == "NumLiteral" && right->value == "0") {
            *node = *left;
            std::cerr << "Algebraic optimization: x + 0 = x" << std::endl;
            return true;
        }
        // 0 + x = x
        if (left->type == "NumLiteral" && left->value == "0") {
            *node = *right;
            std::cerr << "Algebraic optimization: 0 + x = x" << std::endl;
            return true;
        }
    }

    // 乘法恒等式优化
    if (node->type == "MulExpr") {
        // x * 0 = 0
        if ((left->type == "NumLiteral" && left->value == "0") ||
            (right->type == "NumLiteral" && right->value == "0")) {
            node->type = "NumLiteral";
            node->value = "0";
            node->children.clear();
            std::cerr << "Algebraic optimization: x * 0 = 0" << std::endl;
            return true;
        }
        // x * 1 = x
        if (right->type == "NumLiteral" && right->value == "1") {
            *node = *left;
            std::cerr << "Algebraic optimization: x * 1 = x" << std::endl;
            return true;
        }
        // 1 * x = x
        if (left->type == "NumLiteral" && left->value == "1") {
            *node = *right;
            std::cerr << "Algebraic optimization: 1 * x = x" << std::endl;
            return true;
        }
    }

    // 逻辑运算恒等式优化
    if (node->type == "LAndExpr") {
        // x && false = false
        if (right->type == "NumLiteral" && right->value == "0") {
            node->type = "NumLiteral";
            node->value = "0";
            node->children.clear();
            std::cerr << "Algebraic optimization: x && false = false" << std::endl;
            return true;
        }
        // false && x = false
        if (left->type == "NumLiteral" && left->value == "0") {
            node->type = "NumLiteral";
            node->value = "0";
            node->children.clear();
            std::cerr << "Algebraic optimization: false && x = false" << std::endl;
            return true;
        }
        // x && true = x
        if (right->type == "NumLiteral" && right->value == "1") {
            *node = *left;
            std::cerr << "Algebraic optimization: x && true = x" << std::endl;
            return true;
        }
        // true && x = x
        if (left->type == "NumLiteral" && left->value == "1") {
            *node = *right;
            std::cerr << "Algebraic optimization: true && x = x" << std::endl;
            return true;
        }
    }

    if (node->type == "LOrExpr") {
        // x || true = true
        if (right->type == "NumLiteral" && right->value == "1") {
            node->type = "NumLiteral";
            node->value = "1";
            node->children.clear();
            std::cerr << "Algebraic optimization: x || true = true" << std::endl;
            return true;
        }
        // true || x = true
        if (left->type == "NumLiteral" && left->value == "1") {
            node->type = "NumLiteral";
            node->value = "1";
            node->children.clear();
            std::cerr << "Algebraic optimization: true || x = true" << std::endl;
            return true;
        }
        // x || false = x
        if (right->type == "NumLiteral" && right->value == "0") {
            *node = *left;
            std::cerr << "Algebraic optimization: x || false = x" << std::endl;
            return true;
        }
        // false || x = x
        if (left->type == "NumLiteral" && left->value == "0") {
            *node = *right;
            std::cerr << "Algebraic optimization: false || x = x" << std::endl;
            return true;
        }
    }

    return false;
}

void ConstantFoldingOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void ConstantFoldingOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 应用代数恒等式优化
    if (applyAlgebraicOptimizations(node)) {
        return; // 如果应用了代数优化，继续处理当前节点
    }

    // 检查是否可以常量折叠
    if (isConstant(node)) {
        int value = evaluateConstant(node);

        // 替换当前节点
        node->type = "NumLiteral";
        node->value = std::to_string(value);
        node->children.clear();

        std::cerr << "Constant folding: " << value << std::endl;
    }
}

// ==================== CommonSubexpressionOptimizer 实现 ====================

std::string CommonSubexpressionOptimizer::getExpressionKey(ASTNode* node) {
    if (!node) return "";

    std::ostringstream oss;
    oss << node->type;

    if (!node->value.empty()) {
        oss << ":" << node->value;
    }

    for (const auto& child : node->children) {
        oss << "(" << getExpressionKey(child.get()) << ")";
    }

    return oss.str();
}

bool CommonSubexpressionOptimizer::isOptimizableExpression(ASTNode* node) {
    if (!node) return false;

    // 检查是否是值得优化的表达式类型
    if (node->type == "AddExpr" || node->type == "MulExpr" ||
        node->type == "RelExpr" || node->type == "LAndExpr" ||
        node->type == "LOrExpr" || node->type == "UnaryExpr") {

        // 确保表达式不是常量（常量折叠已经处理过了）
        if (node->type == "NumLiteral") return false;

        // 确保表达式有足够的复杂度（至少有一个变量引用）
        return hasVariableReference(node);
    }

    return false;
}

bool CommonSubexpressionOptimizer::hasVariableReference(ASTNode* node) {
    if (!node) return false;

    if (node->type == "VarRef") return true;

    for (const auto& child : node->children) {
        if (hasVariableReference(child.get())) return true;
    }

    return false;
}

std::string CommonSubexpressionOptimizer::createTempVariable() {
    return "_temp_" + std::to_string(tempVarCounter++);
}

ASTNode* CommonSubexpressionOptimizer::createVarRefNode(const std::string& varName) {
    return new ASTNode("VarRef", varName);
}

ASTNode* CommonSubexpressionOptimizer::createAssignNode(const std::string& varName, ASTNode* expr) {
    ASTNode* assignNode = new ASTNode("AssignStmt");
    assignNode->addChild(createVarRefNode(varName));
    assignNode->addChild(expr);
    return assignNode;
}

void CommonSubexpressionOptimizer::optimize(ASTNode* root) {
    if (!root) return;

    // 重置状态
    expressionMap.clear();
    tempVarMap.clear();
    tempVarCounter = 0;

    // 对每个函数进行优化
    if (root->type == "CompUnit") {
        for (auto& child : root->children) {
            if (child->type == "FuncDef") {
                optimizeFunction(child.get());
            }
        }
    } else {
        optimizeNode(root);
    }
}

void CommonSubexpressionOptimizer::optimizeFunction(ASTNode* funcNode) {
    if (!funcNode || funcNode->type != "FuncDef") return;

    // 找到函数体
    ASTNode* bodyNode = nullptr;
    for (auto& child : funcNode->children) {
        if (child->type == "Block") {
            bodyNode = child.get();
            break;
        }
    }

    if (bodyNode) {
        optimizeBlock(bodyNode);
    }
}

void CommonSubexpressionOptimizer::optimizeBlock(ASTNode* blockNode) {
    if (!blockNode || blockNode->type != "Block") return;

    std::vector<std::unique_ptr<ASTNode>> optimizedStatements;

    for (auto& stmt : blockNode->children) {
        if (stmt->type == "Expr") {
            // 对表达式语句进行优化
            optimizeExpressionStatement(stmt.get(), optimizedStatements);
        } else {
            // 其他语句直接添加
            optimizedStatements.push_back(std::move(stmt));
        }
    }

    // 替换原语句列表
    blockNode->children = std::move(optimizedStatements);
}

void CommonSubexpressionOptimizer::optimizeExpressionStatement(ASTNode* exprStmt,
                                                              std::vector<std::unique_ptr<ASTNode>>& optimizedStatements) {
    if (!exprStmt || exprStmt->type != "Expr") return;

    ASTNode* expr = exprStmt->children.empty() ? nullptr : exprStmt->children[0].get();
    if (!expr) return;

    // 先优化子表达式
    optimizeNode(expr);

    // 检查是否可以进行公共子表达式消除
    if (isOptimizableExpression(expr)) {
        std::string key = getExpressionKey(expr);

        auto it = expressionMap.find(key);
        if (it != expressionMap.end()) {
            // 找到公共子表达式
            std::cerr << "Common subexpression found: " << key << std::endl;

            // 检查是否已经有临时变量存储这个表达式
            auto tempIt = tempVarMap.find(key);
            if (tempIt != tempVarMap.end()) {
                // 使用已有的临时变量
                std::string tempVar = tempIt->second;
                ASTNode* varRef = createVarRefNode(tempVar);
                exprStmt->children.clear();
                exprStmt->children.emplace_back(varRef);
                std::cerr << "Reusing temporary variable: " << tempVar << std::endl;
            } else {
                // 创建新的临时变量
                std::string tempVar = createTempVariable();
                tempVarMap[key] = tempVar;

                // 创建赋值语句
                ASTNode* assignStmt = createAssignNode(tempVar, expr);
                optimizedStatements.emplace_back(assignStmt);

                // 替换原表达式为变量引用
                ASTNode* varRef = createVarRefNode(tempVar);
                exprStmt->children.clear();
                exprStmt->children.emplace_back(varRef);

                std::cerr << "Created temporary variable: " << tempVar << " for expression: " << key << std::endl;
            }
        } else {
            // 记录这个表达式
            expressionMap[key] = expr;
        }
    }

    optimizedStatements.emplace_back(std::move(exprStmt));
}

void CommonSubexpressionOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 检查是否是表达式节点
    if (isOptimizableExpression(node)) {
        std::string key = getExpressionKey(node);

        // 检查是否已经存在相同的表达式
        auto it = expressionMap.find(key);
        if (it != expressionMap.end()) {
            // 找到公共子表达式，可以重用
            std::cerr << "Common subexpression found in nested expression: " << key << std::endl;

            // 检查是否已经有临时变量
            auto tempIt = tempVarMap.find(key);
            if (tempIt != tempVarMap.end()) {
                // 替换为变量引用
                std::string tempVar = tempIt->second;
                ASTNode* varRef = createVarRefNode(tempVar);
                *node = *varRef;
                delete varRef;
                std::cerr << "Replaced with temporary variable: " << tempVar << std::endl;
            }
        } else {
            // 记录这个表达式
            expressionMap[key] = node;
        }
    }
}

// ==================== DeadCodeEliminator 实现 ====================

bool DeadCodeEliminator::isDeadCode(ASTNode* node) {
    if (!node) return false;

    // 检查是否是未使用的变量声明
    if (node->type == "DeclAssignStmt") {
        return isUnusedVariable(node);
    }

    // 检查是否是未使用的表达式语句
    if (node->type == "Expr") {
        return !hasSideEffects(node);
    }

    // 检查是否是不可达代码
    if (isUnreachableCode(node)) {
        return true;
    }

    return false;
}

bool DeadCodeEliminator::hasSideEffects(ASTNode* node) {
    if (!node) return false;

    // 函数调用有副作用
    if (node->type == "FuncCall") {
        return true;
    }

    // 赋值语句有副作用
    if (node->type == "AssignStmt") {
        return true;
    }

    // 递归检查子节点
    for (const auto& child : node->children) {
        if (hasSideEffects(child.get())) {
            return true;
        }
    }

    return false;
}

bool DeadCodeEliminator::isUnreachableCode(ASTNode* node) {
    if (!node) return false;

    // 检查是否在return语句之后
    // 这个检查在optimizeBlock中已经处理

    // 检查是否在无限循环之后
    // 这里可以添加更复杂的控制流分析

    return false;
}

bool DeadCodeEliminator::isUnusedVariable(ASTNode* node) {
    if (!node || node->type != "DeclAssignStmt") return false;

    // 找到变量名
    std::string varName;
    for (const auto& child : node->children) {
        if (child->type == "ID") {
            varName = child->value;
            break;
        }
    }

    if (varName.empty()) return false;

    // 检查变量是否被使用
    return usedVariables.find(varName) == usedVariables.end();
}

void DeadCodeEliminator::collectUsedVariables(ASTNode* node) {
    if (!node) return;

    // 收集变量引用
    if (node->type == "VarRef") {
        usedVariables.insert(node->value);
    }

    // 递归处理子节点
    for (const auto& child : node->children) {
        collectUsedVariables(child.get());
    }
}

void DeadCodeEliminator::collectDefinedVariables(ASTNode* node) {
    if (!node) return;

    // 收集变量定义
    if (node->type == "DeclAssignStmt") {
        for (const auto& child : node->children) {
            if (child->type == "ID") {
                definedVariables.insert(child->value);
                break;
            }
        }
    }

    // 递归处理子节点
    for (const auto& child : node->children) {
        collectDefinedVariables(child.get());
    }
}

bool DeadCodeEliminator::isControlFlowStatement(ASTNode* node) {
    if (!node) return false;

    return node->type == "IfStmt" || node->type == "WhileStmt" ||
           node->type == "ReturnStmt" || node->type == "BreakStmt" ||
           node->type == "ContinueStmt";
}

bool DeadCodeEliminator::hasReturnStatement(ASTNode* node) {
    if (!node) return false;

    if (node->type == "ReturnStmt") return true;

    for (const auto& child : node->children) {
        if (hasReturnStatement(child.get())) return true;
    }

    return false;
}

void DeadCodeEliminator::optimize(ASTNode* root) {
    if (!root) return;

    // 重置状态
    usedVariables.clear();
    definedVariables.clear();

    // 对每个函数进行优化
    if (root->type == "CompUnit") {
        for (auto& child : root->children) {
            if (child->type == "FuncDef") {
                optimizeFunction(child.get());
            }
        }
    } else {
        optimizeNode(root);
    }
}

void DeadCodeEliminator::optimizeFunction(ASTNode* funcNode) {
    if (!funcNode || funcNode->type != "FuncDef") return;

    // 重置函数级别的状态
    usedVariables.clear();
    definedVariables.clear();

    // 找到函数体
    ASTNode* bodyNode = nullptr;
    for (auto& child : funcNode->children) {
        if (child->type == "Block") {
            bodyNode = child.get();
            break;
        }
    }

    if (bodyNode) {
        // 先收集所有变量使用和定义
        collectUsedVariables(bodyNode);
        collectDefinedVariables(bodyNode);

        // 然后进行死代码消除
        optimizeBlock(bodyNode);
    }
}

void DeadCodeEliminator::optimizeBlock(ASTNode* blockNode) {
    if (!blockNode || blockNode->type != "Block") return;

    std::vector<std::unique_ptr<ASTNode>> optimizedStatements;
    bool hasReturn = false;

    for (auto& stmt : blockNode->children) {
        // 如果已经遇到return语句，后续代码都是不可达的
        if (hasReturn) {
            std::cerr << "Dead code elimination: unreachable code after return" << std::endl;
            continue; // 跳过不可达代码
        }

        // 检查是否是return语句
        if (stmt->type == "ReturnStmt") {
            hasReturn = true;
            optimizedStatements.push_back(std::move(stmt));
            continue;
        }

        // 检查是否是死代码
        if (isDeadCode(stmt.get())) {
            std::cerr << "Dead code elimination: " << stmt->type << std::endl;
            continue; // 跳过死代码
        }

        // 递归优化子节点
        optimizeNode(stmt.get());

        // 保留非死代码
        optimizedStatements.push_back(std::move(stmt));
    }

    // 替换原语句列表
    blockNode->children = std::move(optimizedStatements);
}

void DeadCodeEliminator::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 检查是否是死代码
    if (isDeadCode(node)) {
        std::cerr << "Dead code elimination: " << node->type << std::endl;
    }
}

// ==================== Optimizer 实现 ====================

void Optimizer::optimize(ASTNode* root) {
    if (!root) return;

    std::cerr << "Starting optimization..." << std::endl;

    if (useAdaptiveOptimization) {
        // 使用自适应优化
        std::cerr << "Using adaptive optimization..." << std::endl;
        analyzeAndOptimize(root);
    } else if (useCoordinatedOptimization) {
        // 使用协调优化
        std::cerr << "Using coordinated optimization..." << std::endl;
        coordinator.coordinateOptimizations(root);
    } else {
        // 使用传统顺序优化
        std::cerr << "Using traditional sequential optimization..." << std::endl;
        optimizeConstantFolding(root);
        optimizeCommonSubexpressions(root);
        optimizeDeadCodeElimination(root);
        //optimizeMatrixOperations(root);
    }

    std::cerr << "Optimization completed." << std::endl;
}

void Optimizer::optimizeConstantFolding(ASTNode* root) {
    std::cerr << "Applying constant folding optimization..." << std::endl;
    constantFolder.optimize(root);
}

void Optimizer::optimizeCommonSubexpressions(ASTNode* root) {
    std::cerr << "Applying common subexpression elimination..." << std::endl;
    cseOptimizer.optimize(root);
}

void Optimizer::optimizeDeadCodeElimination(ASTNode* root) {
    std::cerr << "Applying dead code elimination..." << std::endl;
    deadCodeEliminator.optimize(root);
}

void Optimizer::optimizeMatrixOperations(ASTNode* root) {
    std::cerr << "Applying matrix operation optimization..." << std::endl;
    matrixOptimizer.optimize(root);
}

void Optimizer::enableCoordinatedOptimization(bool enable) {
    useCoordinatedOptimization = enable;
    std::cerr << "Coordinated optimization " << (enable ? "enabled" : "disabled") << std::endl;
}

void Optimizer::setOptimizationStrategy(const std::vector<OptimizationType>& strategy) {
    coordinator.setOptimizationOrder(strategy);
    std::cerr << "Optimization strategy updated with " << strategy.size() << " optimizations" << std::endl;
}

void Optimizer::setOptimizationLevel(int level) {
    // 根据优化级别设置不同的策略
    std::vector<OptimizationType> strategy;

    switch (level) {
        case 0: // 无优化
            strategy = {};
            break;
        case 1: // 基本优化
            strategy = {
                OptimizationType::CONSTANT_FOLDING,
                OptimizationType::DEAD_CODE_ELIMINATION
            };
            break;
        case 2: // 标准优化
            strategy = {
                OptimizationType::CONSTANT_FOLDING,
                OptimizationType::ALGEBRAIC_OPTIMIZATION,
                OptimizationType::COMMON_SUBEXPRESSION_ELIMINATION,
                OptimizationType::DEAD_CODE_ELIMINATION
            };
            break;
        case 3: // 激进优化
            strategy = {
                OptimizationType::CONSTANT_FOLDING,
                OptimizationType::ALGEBRAIC_OPTIMIZATION,
                OptimizationType::COMMON_SUBEXPRESSION_ELIMINATION,
                OptimizationType::DEAD_CODE_ELIMINATION,
                OptimizationType::LOOP_OPTIMIZATION,
                OptimizationType::REGISTER_ALLOCATION,
                OptimizationType::INLINING,
                OptimizationType::VECTORIZATION
            };
            break;
        default:
            strategy = {
                OptimizationType::CONSTANT_FOLDING,
                OptimizationType::ALGEBRAIC_OPTIMIZATION,
                OptimizationType::COMMON_SUBEXPRESSION_ELIMINATION,
                OptimizationType::DEAD_CODE_ELIMINATION
            };
            break;
    }

    setOptimizationStrategy(strategy);
    std::cerr << "Optimization level set to " << level << std::endl;
}

void Optimizer::enableAdaptiveOptimization(bool enable) {
    useAdaptiveOptimization = enable;
    std::cerr << "Adaptive optimization " << (enable ? "enabled" : "disabled") << std::endl;
}

void Optimizer::analyzeAndOptimize(ASTNode* root) {
    if (!root) return;

    std::cerr << "Starting adaptive optimization analysis..." << std::endl;

    // 分析代码特征
    codeAnalyzer.analyzeCode(root);

    // 获取优化策略建议
    OptimizationStrategy strategy = getOptimizationStrategy(root);

    // 根据建议应用优化
    applyAdaptiveOptimizations(root, strategy);
}

OptimizationStrategy Optimizer::getOptimizationStrategy(ASTNode* root) {
    return codeAnalyzer.suggestOptimizationStrategy();
}

void Optimizer::applyAdaptiveOptimizations(ASTNode* root, const OptimizationStrategy& strategy) {
    std::cerr << "Applying adaptive optimizations based on code analysis..." << std::endl;
    std::cerr << "Suggested optimization level: " << strategy.suggestedOptimizationLevel << std::endl;
    std::cerr << "Reasoning: " << strategy.reasoning << std::endl;

    // 应用推荐的优化
    for (auto optimization : strategy.recommendedOptimizations) {
        std::cerr << "Applying recommended optimization: " << static_cast<int>(optimization) << std::endl;
        applyOptimization(root, optimization);
    }

    // 根据优化级别决定是否应用可选优化
    if (strategy.suggestedOptimizationLevel >= 2) {
        for (auto optimization : strategy.optionalOptimizations) {
            std::cerr << "Applying optional optimization: " << static_cast<int>(optimization) << std::endl;
            applyOptimization(root, optimization);
        }
    }

    // 根据优化级别决定是否应用激进优化
    if (strategy.suggestedOptimizationLevel >= 3) {
        for (auto optimization : strategy.aggressiveOptimizations) {
            std::cerr << "Applying aggressive optimization: " << static_cast<int>(optimization) << std::endl;
            applyOptimization(root, optimization);
        }
    }
}

void Optimizer::applyOptimization(ASTNode* root, OptimizationType optimization) {
    switch (optimization) {
        case OptimizationType::CONSTANT_FOLDING:
            optimizeConstantFolding(root);
            break;
        case OptimizationType::COMMON_SUBEXPRESSION_ELIMINATION:
            optimizeCommonSubexpressions(root);
            break;
        case OptimizationType::DEAD_CODE_ELIMINATION:
            optimizeDeadCodeElimination(root);
            break;
        case OptimizationType::ALGEBRAIC_OPTIMIZATION:
            // 代数优化已经集成在常量折叠中
            break;
        case OptimizationType::LOOP_OPTIMIZATION:
            optimizeLoopOperations(root);
            break;
        case OptimizationType::REGISTER_ALLOCATION:
            optimizeRegisterAllocation(root);
            break;
        case OptimizationType::INLINING:
            optimizeInlining(root);
            break;
        case OptimizationType::VECTORIZATION:
            optimizeVectorization(root);
            break;
        default:
            std::cerr << "Unknown optimization type: " << static_cast<int>(optimization) << std::endl;
            break;
    }
}

// ==================== 新增优化器方法实现 ====================

void Optimizer::optimizeLoopOperations(ASTNode* root) {
    std::cerr << "Applying loop optimization..." << std::endl;
    loopOptimizer.optimize(root);
}

void Optimizer::optimizeRegisterAllocation(ASTNode* root) {
    std::cerr << "Applying register allocation optimization..." << std::endl;
    registerAllocator.optimize(root);
}

void Optimizer::optimizeInlining(ASTNode* root) {
    std::cerr << "Applying function inlining optimization..." << std::endl;
    inliningOptimizer.optimize(root);
}

void Optimizer::optimizeVectorization(ASTNode* root) {
    std::cerr << "Applying vectorization optimization..." << std::endl;
    vectorizationOptimizer.optimize(root);
}

// ==================== LoopOptimizer 实现 ====================

void LoopOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void LoopOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 检查是否是循环节点
    if (node->type == "WhileStmt" || node->type == "ForStmt") {
        optimizeLoop(node);
    }
}

void LoopOptimizer::optimizeLoop(ASTNode* loopNode) {
    if (!loopNode) return;

    std::cerr << "Loop optimization: " << loopNode->type << std::endl;

    // 识别循环变量
    identifyLoopVariables(loopNode);

    // 循环不变量外提
    hoistInvariants(loopNode);

    // 强度削弱
    strengthReduction(loopNode);
}

void LoopOptimizer::identifyLoopVariables(ASTNode* loopNode) {
    if (!loopNode) return;

    loopVariables.clear();

    // 查找循环变量（在循环条件中变化的变量）
    if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        // For循环的初始化部分
        ASTNode* init = loopNode->children[0].get();
        if (init && init->type == "AssignStmt") {
            for (const auto& child : init->children) {
                if (child->type == "ID") {
                    loopVariables.insert(child->value);
                    break;
                }
            }
        }
    }

    // 查找循环体中的变量赋值
    ASTNode* body = nullptr;
    if (loopNode->type == "WhileStmt" && loopNode->children.size() >= 1) {
        body = loopNode->children[0].get();
    } else if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        body = loopNode->children[2].get();
    }

    if (body) {
        // 递归查找循环体中的变量赋值
        std::function<void(ASTNode*)> findAssignments = [&](ASTNode* node) {
            if (!node) return;
            if (node->type == "AssignStmt") {
                for (const auto& child : node->children) {
                    if (child->type == "ID") {
                        loopVariables.insert(child->value);
                        break;
                    }
                }
            }
            for (const auto& child : node->children) {
                findAssignments(child.get());
            }
        };
        findAssignments(body);
    }
}

bool LoopOptimizer::isLoopVariable(const std::string& varName) {
    return loopVariables.find(varName) != loopVariables.end();
}

bool LoopOptimizer::isLoopInvariant(ASTNode* node, const std::set<std::string>& loopVars) {
    if (!node) return true;

    // 如果是变量引用，检查是否是循环变量
    if (node->type == "VarRef") {
        return loopVars.find(node->value) == loopVars.end();
    }

    // 如果是常量，则是不变量
    if (node->type == "NumLiteral") {
        return true;
    }

    // 递归检查子节点
    for (const auto& child : node->children) {
        if (!isLoopInvariant(child.get(), loopVars)) {
            return false;
        }
    }

    return true;
}

void LoopOptimizer::hoistInvariants(ASTNode* loopNode) {
    if (!loopNode) return;

    // 查找循环体
    ASTNode* body = nullptr;
    if (loopNode->type == "WhileStmt" && loopNode->children.size() >= 1) {
        body = loopNode->children[0].get();
    } else if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        body = loopNode->children[2].get();
    }

    if (!body || body->type != "Block") return;

    std::vector<std::unique_ptr<ASTNode>> hoistedStatements;
    std::vector<std::unique_ptr<ASTNode>> remainingStatements;

    for (auto& stmt : body->children) {
        if (isLoopInvariant(stmt.get(), loopVariables)) {
            // 外提循环不变量
            hoistedStatements.push_back(std::move(stmt));
            std::cerr << "Loop invariant hoisting: " << stmt->type << std::endl;
        } else {
            remainingStatements.push_back(std::move(stmt));
        }
    }

    // 重新组织循环体
    body->children.clear();
    for (auto& stmt : remainingStatements) {
        body->children.push_back(std::move(stmt));
    }

    // 将外提的语句插入到循环之前
    // 这里需要找到循环的父节点来插入外提的语句
    // 简化实现：暂时只记录外提的语句
    for (auto& stmt : hoistedStatements) {
        loopInvariants[stmt->type] = stmt.get();
        std::cerr << "Loop invariant hoisted: " << stmt->type << " (stored for later insertion)" << std::endl;
    }

    // 在实际实现中，这里应该：
    // 1. 找到循环的父节点
    // 2. 在循环之前插入外提的语句
    // 3. 从循环体中移除这些语句
    std::cerr << "Hoisted " << hoistedStatements.size() << " invariant statements from loop" << std::endl;
}

bool LoopOptimizer::canStrengthReduce(ASTNode* node) {
    if (!node) return false;

    // 检查是否是乘法运算，其中一个操作数是循环变量
    if (node->type == "MulExpr" && node->children.size() == 2) {
        ASTNode* left = node->children[0].get();
        ASTNode* right = node->children[1].get();

        bool leftIsLoopVar = (left->type == "VarRef" && isLoopVariable(left->value));
        bool rightIsLoopVar = (right->type == "VarRef" && isLoopVariable(right->value));

        return (leftIsLoopVar && right->type == "NumLiteral") ||
               (rightIsLoopVar && left->type == "NumLiteral");
    }

    return false;
}

void LoopOptimizer::strengthReduction(ASTNode* loopNode) {
    if (!loopNode) return;

    // 查找循环体中的强度削弱机会
    std::function<void(ASTNode*)> reduceStrength = [&](ASTNode* node) {
        if (!node) return;

        if (canStrengthReduce(node)) {
            std::cerr << "Strength reduction: " << node->type << std::endl;

            // 实现强度削弱：将乘法转换为加法
            // 例如：i * 2 转换为 i + i
            ASTNode* left = node->children[0].get();
            ASTNode* right = node->children[1].get();

            if (left->type == "VarRef" && isLoopVariable(left->value) && right->type == "NumLiteral") {
                int multiplier = std::stoi(right->value);
                if (multiplier == 2) {
                    // i * 2 -> i + i
                    node->type = "AddExpr";
                    node->value = "+";
                    node->children.clear();
                    node->addChild(new ASTNode(*left));  // 复制左操作数
                    node->addChild(new ASTNode(*left));  // 复制左操作数
                    std::cerr << "Strength reduction: " << left->value << " * 2 -> " << left->value << " + " << left->value << std::endl;
                } else if (multiplier == 4) {
                    // i * 4 -> (i + i) + (i + i)
                    node->type = "AddExpr";
                    node->value = "+";
                    node->children.clear();

                    ASTNode* leftAdd = new ASTNode("AddExpr", "+");
                    leftAdd->addChild(new ASTNode(*left));
                    leftAdd->addChild(new ASTNode(*left));

                    ASTNode* rightAdd = new ASTNode("AddExpr", "+");
                    rightAdd->addChild(new ASTNode(*left));
                    rightAdd->addChild(new ASTNode(*left));

                    node->addChild(leftAdd);
                    node->addChild(rightAdd);
                    std::cerr << "Strength reduction: " << left->value << " * 4 -> (" << left->value << " + " << left->value << ") + (" << left->value << " + " << left->value << ")" << std::endl;
                }
            } else if (right->type == "VarRef" && isLoopVariable(right->value) && left->type == "NumLiteral") {
                int multiplier = std::stoi(left->value);
                if (multiplier == 2) {
                    // 2 * i -> i + i
                    node->type = "AddExpr";
                    node->value = "+";
                    node->children.clear();
                    node->addChild(new ASTNode(*right));
                    node->addChild(new ASTNode(*right));
                    std::cerr << "Strength reduction: 2 * " << right->value << " -> " << right->value << " + " << right->value << std::endl;
                }
            }
        }

        for (auto& child : node->children) {
            reduceStrength(child.get());
        }
    };

    // 在循环体中查找
    if (loopNode->type == "WhileStmt" && loopNode->children.size() >= 1) {
        reduceStrength(loopNode->children[0].get());
    } else if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        reduceStrength(loopNode->children[2].get());
    }
}

// ==================== RegisterAllocationOptimizer 实现 ====================

void RegisterAllocationOptimizer::initializeRegisters() {
    // 初始化空闲寄存器栈
    for (int i = 31; i >= 0; i--) {
        freeRegisters.push(i);
    }
    nextRegister = 0;
}

int RegisterAllocationOptimizer::allocateRegister(const std::string& varName) {
    if (variableRegisters.find(varName) != variableRegisters.end()) {
        return variableRegisters[varName];
    }

    int reg;
    if (!freeRegisters.empty()) {
        reg = freeRegisters.top();
        freeRegisters.pop();
    } else {
        // 寄存器不足，需要溢出
        reg = nextRegister++;
        if (nextRegister >= maxRegisters) {
            spillRegister(reg);
            return reg;
        }
    }

    variableRegisters[varName] = reg;
    registerVariables[reg] = varName;
    std::cerr << "Allocated register " << reg << " for variable " << varName << std::endl;
    return reg;
}

void RegisterAllocationOptimizer::freeRegister(int reg) {
    if (registerVariables.find(reg) != registerVariables.end()) {
        std::string varName = registerVariables[reg];
        variableRegisters.erase(varName);
        registerVariables.erase(reg);
        freeRegisters.push(reg);
        std::cerr << "Freed register " << reg << " from variable " << varName << std::endl;
    }
}

void RegisterAllocationOptimizer::spillRegister(int reg) {
    std::cerr << "Register spill: register " << reg << " spilled to memory" << std::endl;

    // 实现寄存器溢出到内存的逻辑
    if (registerVariables.find(reg) != registerVariables.end()) {
        std::string varName = registerVariables[reg];

        // 计算溢出地址（简化实现）
        int spillOffset = -(reg + 1) * 4;  // 每个寄存器占用4字节

        // 生成溢出指令
        std::cerr << "Spilling variable " << varName << " from register " << reg
                  << " to memory offset " << spillOffset << std::endl;

        // 在实际实现中，这里会生成相应的汇编指令
        // 例如：sw $reg, spillOffset($sp)
    }
}

void RegisterAllocationOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void RegisterAllocationOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 为变量分配寄存器
    if (node->type == "VarRef") {
        allocateRegister(node->value);
    } else if (node->type == "DeclAssignStmt") {
        // 变量声明时分配寄存器
        for (const auto& child : node->children) {
            if (child->type == "ID") {
                allocateRegister(child->value);
                break;
            }
        }
    }
}

void RegisterAllocationOptimizer::optimizeFunction(ASTNode* funcNode) {
    if (!funcNode || funcNode->type != "FuncDef") return;

    // 分析函数中的活跃变量
    analyzeLiveness(funcNode);

    // 优化寄存器使用
    optimizeRegisterUsage(funcNode);
}

void RegisterAllocationOptimizer::analyzeLiveness(ASTNode* node) {
    if (!node) return;

    // 简单的活跃变量分析
    if (node->type == "VarRef") {
        // 变量被使用，标记为活跃
        std::cerr << "Variable " << node->value << " is live" << std::endl;
    }

    for (const auto& child : node->children) {
        analyzeLiveness(child.get());
    }
}

std::set<std::string> RegisterAllocationOptimizer::getLiveVariables(ASTNode* node) {
    std::set<std::string> liveVars;
    if (!node) return liveVars;

    if (node->type == "VarRef") {
        liveVars.insert(node->value);
    }

    for (const auto& child : node->children) {
        auto childVars = getLiveVariables(child.get());
        liveVars.insert(childVars.begin(), childVars.end());
    }

    return liveVars;
}

void RegisterAllocationOptimizer::optimizeRegisterUsage(ASTNode* node) {
    if (!node) return;

    // 优化寄存器使用策略
    // 这里可以实现更复杂的寄存器分配算法
    // 例如：图着色算法、线性扫描等

    for (auto& child : node->children) {
        optimizeRegisterUsage(child.get());
    }
}

// ==================== InliningOptimizer 实现 ====================

void InliningOptimizer::optimize(ASTNode* root) {
    if (!root) return;

    // 收集所有函数定义
    collectFunctionDefinitions(root);

    // 优化内联
    optimizeNode(root);
}

void InliningOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 检查是否是函数调用
    if (node->type == "FuncCall") {
        // 查找函数名
        std::string funcName;
        if (!node->children.empty() && node->children[0]->type == "ID") {
            funcName = node->children[0]->value;
        }

        if (!funcName.empty() && shouldInline(funcName)) {
            std::cerr << "Function inlining: " << funcName << std::endl;

            auto it = functionDefinitions.find(funcName);
            if (it != functionDefinitions.end()) {
                // 创建内联函数
                ASTNode* inlinedFunc = createInlinedFunction(node, it->second);
                if (inlinedFunc) {
                    // 替换函数调用为内联代码
                    *node = *inlinedFunc;
                    delete inlinedFunc;
                }
            }
        }
    }
}

void InliningOptimizer::collectFunctionDefinitions(ASTNode* root) {
    if (!root) return;

    if (root->type == "FuncDef") {
        // 找到函数名
        std::string funcName;
        for (const auto& child : root->children) {
            if (child->type == "ID") {
                funcName = child->value;
                break;
            }
        }

        if (!funcName.empty()) {
            functionDefinitions[funcName] = root;
            functionSizes[funcName] = calculateFunctionSize(root);
            std::cerr << "Function definition collected: " << funcName
                      << " (size: " << functionSizes[funcName] << ")" << std::endl;
        }
    }

    for (const auto& child : root->children) {
        collectFunctionDefinitions(child.get());
    }
}

int InliningOptimizer::calculateFunctionSize(ASTNode* funcNode) {
    if (!funcNode) return 0;

    int size = 1; // 当前节点
    for (const auto& child : funcNode->children) {
        size += calculateFunctionSize(child.get());
    }

    return size;
}

bool InliningOptimizer::shouldInline(const std::string& funcName) {
    auto it = functionSizes.find(funcName);
    if (it == functionSizes.end()) return false;

    // 检查函数大小是否适合内联
    return it->second <= maxInlineSize && inlineDepth < 3;
}

ASTNode* InliningOptimizer::createInlinedFunction(ASTNode* callNode, ASTNode* funcDef) {
    if (!callNode || !funcDef) return nullptr;

    // 找到函数体
    ASTNode* funcBody = nullptr;
    for (const auto& child : funcDef->children) {
        if (child->type == "Block") {
            funcBody = child.get();
            break;
        }
    }

    if (!funcBody) return nullptr;

    // 创建内联的函数体副本
    ASTNode* inlinedBody = new ASTNode(*funcBody);

    // 替换参数
    std::vector<ASTNode*> args;
    for (size_t i = 1; i < callNode->children.size(); i++) {
        args.push_back(callNode->children[i].get());
    }
    substituteParameters(inlinedBody, args);

    return inlinedBody;
}

void InliningOptimizer::substituteParameters(ASTNode* inlinedBody, const std::vector<ASTNode*>& args) {
    if (!inlinedBody) return;

    // 实现参数替换逻辑
    std::cerr << "Parameter substitution with " << args.size() << " arguments" << std::endl;

    // 递归替换参数
    std::function<void(ASTNode*)> substitute = [&](ASTNode* node) {
        if (!node) return;

        // 如果是参数引用，进行替换
        if (node->type == "VarRef") {
            // 这里应该根据参数名进行替换
            // 简化实现：假设参数按顺序对应
            for (size_t i = 0; i < args.size(); i++) {
                // 在实际实现中，需要根据参数名进行匹配
                // 这里只是示例
                if (node->value == "param" + std::to_string(i)) {
                    // 替换为实际参数
                    *node = *args[i];
                    std::cerr << "Parameter substitution: " << "param" + std::to_string(i)
                              << " -> " << args[i]->value << std::endl;
                    break;
                }
            }
        }

        // 递归处理子节点
        for (auto& child : node->children) {
            substitute(child.get());
        }
    };

    substitute(inlinedBody);
}

std::string InliningOptimizer::generateUniqueName(const std::string& base) {
    static int counter = 0;
    return base + "_" + std::to_string(counter++);
}

void InliningOptimizer::optimizeFunction(ASTNode* funcNode) {
    if (!funcNode || funcNode->type != "FuncDef") return;

    // 在函数内部进行内联优化
    optimizeNode(funcNode);
}

// ==================== VectorizationOptimizer 实现 ====================

VectorizationOptimizer::VectorizationOptimizer() {
    // 初始化可向量化的操作
    vectorizableOperations = {
        "AddExpr", "MulExpr", "RelExpr"
    };
}

void VectorizationOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void VectorizationOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;

    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }

    // 检查是否是循环节点
    if (node->type == "WhileStmt" || node->type == "ForStmt") {
        optimizeLoop(node);
    }
}

void VectorizationOptimizer::optimizeLoop(ASTNode* loopNode) {
    if (!loopNode) return;

    if (isVectorizableLoop(loopNode)) {
        std::cerr << "Vectorization: " << loopNode->type << std::endl;

        // 创建向量化循环
        ASTNode* vectorizedLoop = createVectorizedLoop(loopNode);
        if (vectorizedLoop) {
            // 替换原循环为向量化循环
            *loopNode = *vectorizedLoop;
            delete vectorizedLoop;
        }
    }
}

bool VectorizationOptimizer::isVectorizableLoop(ASTNode* loopNode) {
    if (!loopNode) return false;

    // 检查循环体
    ASTNode* body = nullptr;
    if (loopNode->type == "WhileStmt" && loopNode->children.size() >= 1) {
        body = loopNode->children[0].get();
    } else if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        body = loopNode->children[2].get();
    }

    if (!body) return false;

    // 检查循环迭代次数
    int iterationCount = getLoopIterationCount(loopNode);
    if (iterationCount < 4) return false; // 太短的循环不值得向量化

    // 检查是否有数据依赖
    if (hasDataDependencies(body)) return false;

    // 检查是否包含可向量化的操作
    return isVectorizableOperation(body);
}

bool VectorizationOptimizer::isVectorizableOperation(ASTNode* node) {
    if (!node) return false;

    // 检查是否是数组访问模式
    if (node->type == "VarRef") {
        // 检查是否是数组元素访问
        return true; // 简化实现
    }

    // 检查是否是向量化操作
    for (const auto& op : vectorizableOperations) {
        if (node->type == op) {
            return true;
        }
    }

    // 递归检查子节点
    for (const auto& child : node->children) {
        if (isVectorizableOperation(child.get())) {
            return true;
        }
    }

    return false;
}

void VectorizationOptimizer::identifyVectorizablePatterns(ASTNode* node) {
    if (!node) return;

    // 识别可向量化的模式
    // 例如：数组的连续访问、简单的算术运算等

    for (const auto& child : node->children) {
        identifyVectorizablePatterns(child.get());
    }
}

ASTNode* VectorizationOptimizer::createVectorizedLoop(ASTNode* originalLoop) {
    if (!originalLoop) return nullptr;

    std::cerr << "Creating vectorized loop" << std::endl;

    // 创建向量化循环
    ASTNode* vectorizedLoop = new ASTNode(*originalLoop);

    // 查找循环体
    ASTNode* body = nullptr;
    if (vectorizedLoop->type == "WhileStmt" && vectorizedLoop->children.size() >= 1) {
        body = vectorizedLoop->children[0].get();
    } else if (vectorizedLoop->type == "ForStmt" && vectorizedLoop->children.size() >= 3) {
        body = vectorizedLoop->children[2].get();
    }

    if (body && body->type == "Block") {
        // 向量化循环体中的操作
        std::function<void(ASTNode*)> vectorize = [&](ASTNode* node) {
            if (!node) return;

            // 向量化算术运算
            if (node->type == "AddExpr" || node->type == "MulExpr") {
                // 将标量运算转换为向量运算
                std::string vectorOp = (node->type == "AddExpr") ? "VectorAdd" : "VectorMul";
                node->type = vectorOp;
                std::cerr << "Vectorized operation: " << node->type << " -> " << vectorOp << std::endl;
            }

            // 递归处理子节点
            for (auto& child : node->children) {
                vectorize(child.get());
            }
        };

        // 对循环体中的每个语句进行向量化
        for (auto& stmt : body->children) {
            vectorize(stmt.get());
        }

        std::cerr << "Vectorized loop created successfully" << std::endl;
    }

    return vectorizedLoop;
}

bool VectorizationOptimizer::hasDataDependencies(ASTNode* loopBody) {
    if (!loopBody) return false;

    std::set<std::string> writtenVars;
    std::set<std::string> readVars;
    bool hasDependency = false;

    // 分析循环体中的数据依赖
    std::function<void(ASTNode*)> analyzeDependencies = [&](ASTNode* node) {
        if (!node) return;

        // 检查写操作
        if (node->type == "AssignStmt" || node->type == "DeclAssignStmt") {
            for (const auto& child : node->children) {
                if (child->type == "ID" || child->type == "VarRef") {
                    std::string varName = child->value;
                    if (readVars.find(varName) != readVars.end()) {
                        // 发现写后读依赖
                        hasDependency = true;
                        std::cerr << "Data dependency detected: write-after-read for variable " << varName << std::endl;
                    }
                    writtenVars.insert(varName);
                }
            }
        }

        // 检查读操作
        if (node->type == "VarRef") {
            std::string varName = node->value;
            if (writtenVars.find(varName) != writtenVars.end()) {
                // 发现读后写依赖
                hasDependency = true;
                std::cerr << "Data dependency detected: read-after-write for variable " << varName << std::endl;
            }
            readVars.insert(varName);
        }

        // 递归检查子节点
        for (const auto& child : node->children) {
            analyzeDependencies(child.get());
        }
    };

    analyzeDependencies(loopBody);

    if (hasDependency) {
        std::cerr << "Loop has data dependencies - cannot vectorize" << std::endl;
    }

    return hasDependency;
}

int VectorizationOptimizer::getLoopIterationCount(ASTNode* loopNode) {
    if (!loopNode) return 0;

    // 尝试计算循环迭代次数
    if (loopNode->type == "ForStmt" && loopNode->children.size() >= 3) {
        // 分析For循环的迭代次数
        ASTNode* init = loopNode->children[0].get();
        ASTNode* condition = loopNode->children[1].get();
        ASTNode* update = loopNode->children[2].get();

        // 尝试从条件中提取迭代次数
        if (condition && condition->type == "RelExpr") {
            ASTNode* left = condition->children[0].get();
            ASTNode* right = condition->children[1].get();

            if (left && right && left->type == "VarRef" && right->type == "NumLiteral") {
                // 例如：i < 100
                if (condition->value == "<") {
                    int limit = std::stoi(right->value);
                    std::cerr << "For loop iteration count estimated: " << limit << std::endl;
                    return limit;
                } else if (condition->value == "<=") {
                    int limit = std::stoi(right->value);
                    std::cerr << "For loop iteration count estimated: " << limit << std::endl;
                    return limit;
                }
            }
        }

        // 默认估计
        std::cerr << "For loop iteration count estimated: 100 (default)" << std::endl;
        return 100;

    } else if (loopNode->type == "WhileStmt" && loopNode->children.size() >= 1) {
        // 分析While循环的迭代次数
        ASTNode* condition = loopNode->children[0].get();

        // 尝试从条件中估计迭代次数
        if (condition && condition->type == "RelExpr") {
            ASTNode* left = condition->children[0].get();
            ASTNode* right = condition->children[1].get();

            if (left && right && left->type == "VarRef" && right->type == "NumLiteral") {
                // 例如：i < 50
                if (condition->value == "<") {
                    int limit = std::stoi(right->value);
                    std::cerr << "While loop iteration count estimated: " << limit << std::endl;
                    return limit;
                }
            }
        }

        // 默认估计
        std::cerr << "While loop iteration count estimated: 50 (default)" << std::endl;
        return 50;
    }

    std::cerr << "Unknown loop type, iteration count estimated: 0" << std::endl;
    return 0;
}
